package com.base.controller;

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.base.po.voip.*;
import com.base.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.base.comm.CommContent;
import com.base.helper.VosHelper;
import com.base.utils.IP;
import com.base.utils.PasswordUtils;
import com.base.utils.PinyinTool;
import com.base.utils.Produce;
import com.base.utils.PinyinTool.Type;

@Controller
@RequestMapping("/admin")
public class content_tianjiashangjia {
	@Autowired
	private LogsService logsService;// log日志
	@Autowired
	private UsersService usersService;
	@Autowired
	private FreeroutesService freeroutesService;
	@Autowired
	private SmsconfigsService smsconfigsService;
	@Autowired
	private UrlconfigService urlconfigService;
	@Autowired
	private BusinessNatureService businessNatureService;

	// 账户信息
	@RequestMapping("/content_tianjiashangjia")
	public ModelAndView index(HttpServletRequest request) throws Exception {
		// 返回ModelAndView
		ModelAndView modelAndView = new ModelAndView();
		if (request.getSession().getAttribute("adminUserId") == null) {
			modelAndView.setViewName("jsp/login");
			return modelAndView;
		}
		String adminUserId = (String) request.getSession().getAttribute("adminUserId");
		// 登陆用户
		Users user = usersService.selectByPrimaryKey(adminUserId);
		// 获取所有费率
		FreeroutesExample freeroutesExample = new FreeroutesExample();
		freeroutesExample.setOrderByClause("CreateTime");
		freeroutesExample.getOredCriteria().add(freeroutesExample.createCriteria().andDatastatusEqualTo(true));
		List<Freeroutes> freeroutes = freeroutesService.selectByExample(freeroutesExample);
		request.setAttribute("freeroutes", freeroutes);
		request.setAttribute("user", user);
		if (adminUserId.equals("0b8a2f00271e40b9aea750264bf1bb58")) {    //来淘惠专属ID
			modelAndView.setViewName("jsp/content_tianjiashangjialth");
		} else {
			modelAndView.setViewName("jsp/content_tianjiashangjia");
		}
		return modelAndView;
	}

	String SUCCESS = "success";

	// 添加商家
	@RequestMapping(value = "/insertShop", method = RequestMethod.POST)
	public void insertShop(HttpServletRequest request, HttpServletResponse response, String username, String password,
						   String email, Date createtime, String loginip, Integer role, String mobile, String freeroute,
						   String parentid, String agentlogo, String prefix, String theme, Boolean nextagent, String androidversion,
						   String androidpath, String iosversion, String iospath, String pic, BigDecimal dkbl, Boolean isshop,
						   Integer type, String shopid, String adid, BigDecimal profitratio, String appkey, String appsecret,
						   String pid, String dappkey, String sqappkey, String appstore, String appid, String keypath,
						   String agentprefix, String oneagent, Boolean isalipay, Boolean isprofit, Boolean isaliprofit,
						   BigDecimal aliprofitratio, Integer calltype, String signid, Integer count, Integer overdraft,
						   Integer regimoney, Integer igtype, Integer regishopmoney, Integer regitime,
						   Byte airrecharge, String cityId, String provinceId, boolean flag, String tuijianren1,
						   String tuijianren2,String address,Integer nature, String jhappid, String jhappkey) throws Exception {
		// 返回参数
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		String adminId = (String) request.getSession().getAttribute("adminUserId");
		Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");

//		if (nature<1){
//			out.print("请选择商家性质！");
//			return;
//		}
			if (adminId == null) {
				out.print("请刷新页面重试！");
				return;
			}
			Users mine = usersService.selectByPrimaryKey(adminId);

			if (mine.getNextagent() == false) {
				out.print("该商家没有开设下级权限！");
				return;
			}

			Users user = usersService.selectByUsername(username);
			String usernamesys = (String) request.getSession().getAttribute("useracc");
			if (aliprofitratio == null) {
				aliprofitratio = new BigDecimal(0);
			}
			if (user != null) {
				logsService.insert(CommContent.TYPE_CREATE, "商户名：" + username, usernamesys + "已存在", true,
						IP.getIpAddr(request));
				out.print("账号名已存在，请重新填写");
				return;
			} else if (password == null || password.equals("")) {
				out.print("密码不能为空");
				return;
			} else {
				String id = Produce.getUUID();
				Users agent = usersService.selectByPrimaryKey(adminId);
				String oemId = agent.getParentid();
				if (agent.getRole() == 1 || agent.getRole() == 0) {
					oemId = agent.getId();
				}
				if (agent.getRole() == 2) {
					oemId = agent.getParentid();
				}
				agentprefix = System.currentTimeMillis() / 1000 + "";
				if (adminUsergrade == 0) {
					agentprefix = System.currentTimeMillis() / 1000 + "";
				} else {
					agentprefix = agent.getAgentprefix();
				}
				if (role == 0 || role == 1) {
					oneagent = agent.getId();
					//TODO 设置专线
					prefix = username;
				} else {
					oneagent = agent.getOneagent();
				}
				if (role == 0 || role == 1) {
					if (overdraft == null) {
						overdraft = 0;
					}
				}
				// TODO 商家添加商家 注册赠送和透支金额为空
				if (role == 2) {
					if (overdraft == null) {
						overdraft = 0;
					}
				}
				System.out.println(role);
				sqappkey = "f75po5gv";// TODO 暂时固定
				// int resultCode = usersService.insert(id, username,
				// PasswordUtils.toPWD(password), email,
				// Produce.getNowDate(), loginip, role, true, mobile, new
				// BigDecimal(0.00), freeroute, oemId,
				// agentlogo, prefix + "专线", theme, false, nextagent,
				// androidversion, androidpath, iosversion, iospath,
				// 0, Produce.plusDay(365, Produce.getNowDate()), pic, dkbl, isshop,
				// type, adminId, adid, profitratio,
				// appkey, appsecret, new BigDecimal(0.00), pid, dappkey, sqappkey,
				// 0, appstore, appid, keypath,
				// agentprefix, oneagent, false, true, isalipay, isprofit,
				// isaliprofit, aliprofitratio,
				// new BigDecimal(0.00), new BigDecimal(0.00), 0, calltype);// 创建商家
				if (regimoney == null) {
					regimoney = 0;
				}
				//TODO 创建代理商 是 暂时默认加1000余额和1000购物余额
				Integer shopmoney = 0;
				BigDecimal money = new BigDecimal(0.00);
				if (role == 0 || role == 1) {
					money = new BigDecimal(1000);
				}
				if (role == 0 || role == 1) {
					shopmoney = 1000;
				}
				System.out.println(regitime);
				if (regitime != null) {

				} else {
					regitime = 15;
				}
				int resultCode = usersService.insert(id, username, PasswordUtils.toPWD(password), email,
						Produce.getNowDate(), loginip, role, true, mobile, money, freeroute, oemId,
						agentlogo, prefix + "专线", theme, false, nextagent, airrecharge, androidversion, androidpath, iosversion, iospath,
						regimoney, regishopmoney, regitime, Produce.plusDay(365, Produce.getNowDate()), pic, dkbl, isshop, type, adminId, adid,
						profitratio, appkey, appsecret, new BigDecimal(0.00), pid, dappkey, sqappkey, overdraft, appstore,
						appid, keypath, agentprefix, oneagent, false, true, isalipay, isprofit, isaliprofit, aliprofitratio,
						new BigDecimal(0.00), new BigDecimal(0.00), shopmoney, igtype, calltype, (byte) 1);// 创建商家

				if (jhappid != null && !jhappid.equals("") && jhappkey != null && !jhappkey.equals("")){
					Users users = usersService.selectByPrimaryKey(id);
					users.setJhappid(jhappid);
					users.setJhappkey(jhappkey);
					usersService.updateByPrimaryKeySelective(users);
				}

				//添加完了商家后开始添加分类
				Users user1=usersService.selectByUsername(username);
				Users tuijianren=usersService.selectByUsername(tuijianren1);
				if (tuijianren==null){
					tuijianren=usersService.selectByUsername(tuijianren2);
				}
				Users cityUser=usersService.selectByUsername(cityId);
				Users provinceUser=usersService.selectByUsername(provinceId);
				if (flag) {
					BusinessNature businessNature = new BusinessNature();
					String[] add=address.split("/");
					switch (add.length){
						case 3:
							businessNature.setAddressArea(add[2]);
						case 2:
							businessNature.setAddressCity(add[1]);
						case 1:
							businessNature.setAddressProvince(add[0]);
					}
					//nature表示添加的商家类型
					switch (nature){
						case 1:

							businessNature.setID(Produce.getUUID());
							businessNature.setUserName(username);
							businessNature.setBusinessId(user1.getId());
							businessNature.setTuijianren(tuijianren.getId());
							businessNature.setStatus(nature.toString());
//							businessNature.setAddress(address);
							businessNatureService.addBussinessNature(businessNature);
							break;
						case 2:
							businessNature.setID(Produce.getUUID());
							businessNature.setUserName(username);
							businessNature.setBusinessId(user1.getId());
							businessNature.setParent(cityUser.getId());
							businessNature.setTuijianren(tuijianren.getId());
							businessNature.setStatus(nature.toString());
//							businessNature.setAddress(address);
							businessNatureService.addBussinessNature(businessNature);
							break;
						case 3:
							businessNature.setID(Produce.getUUID());
							businessNature.setUserName(username);
							businessNature.setBusinessId(user1.getId());
							businessNature.setParent(provinceUser.getId());
							businessNature.setStatus(nature.toString());
//							businessNature.setAddress(address);
							businessNatureService.addBussinessNature(businessNature);
					}
	}
				// 创建pinyin下载地址
				PinyinTool tool = new PinyinTool();
				Urlconfig uu = new Urlconfig();
				uu.setCreatetime(Produce.getNowDate());
				uu.setOemid(id);
				uu.setPinyin(tool.toPinYin(username, "", Type.LOWERCASE));
				urlconfigService.insert(uu);
				if (count == null) {
					count = 0;
				}
				if (role == 1) {
					if (signid == null) {
						out.print("请填写短信验证Id");
						return;
					} else {
						Smsconfigs record = new Smsconfigs(Produce.getUUID(), id,
								"http://www.zypaas.com:9988/V1/Account/ACCf472db2f5af843538184f7286e261a57/sms/sureTempalteSend",
								count, "mtl4r3025VTI852j", signid, "mtlg94eI81V6Vs3r", "mtl4bW0612032418", true, 2,
								"application/json");
						smsconfigsService.insert(record);
					}
				}
				if (adminUsergrade == 0) {
					String ag = "";
					if (mine.getUsername().equals("admin")) {

					} else {
						ag = mine.getUsername().trim();
					}
					VosHelper.CreateVosAccount("{\"account\":\"" + username + "\",\"name\":\"" + username
							+ "\",\"money\":\"999999999\",\"limitMoney\":\"0\",\"feeRateGroup\":\"" + freeroute
							+ "\",\"type\":\"0\",\"lockType\":\"0\",\"agentAccount\":\"" + ag
							+ "\",\"phoneBookLimit\":\"0\",\"validTime\":\""
							+ Produce.plusDay(365, Produce.getNowDate()).getTime() + "\"}");
					VosHelper.CreateVosAccount("{\"account\":\"" + username + "j\",\"name\":\"" + username
							+ "j\",\"money\":\"0\",\"limitMoney\":\"0\",\"feeRateGroup\":\"0.006\",\"type\":\"2\",\"lockType\":\"0\",\"agentAccount\":\""
							+ "\",\"phoneBookLimit\":\"0\",\"validTime\":\""
							+ Produce.plusDay(365, Produce.getNowDate()).getTime() + "\"}");
				} else {
					VosHelper.CreateVosAccount("{\"account\":\"" + username + "\",\"name\":\"" + username
							+ "\",\"money\":\"999999999\",\"limitMoney\":\"0\",\"feeRateGroup\":\"" + freeroute
							+ "\",\"type\":\"0\",\"lockType\":\"0\",\"agentAccount\":\"" + mine.getUsername().trim()
							+ "\",\"phoneBookLimit\":\"0\",\"validTime\":\""
							+ Produce.plusDay(365, Produce.getNowDate()).getTime() + "\"}");
				}
				if (resultCode == 1) {
					logsService.insert(CommContent.TYPE_CREATE, "成功创建商户/流量代理商：" + username, usernamesys, true,
							IP.getIpAddr(request));
					out.print(SUCCESS);
				} else {
					logsService.insert(CommContent.TYPE_CREATE, "创建商户/流量代理商：" + username, usernamesys + "时失败了", true,
							IP.getIpAddr(request));
					out.print("更改失败，请您重试");
				}

		   }
	}
}
